import liushi
import bayes_opt
import pickle
from feature import company

print('import finished')

f=open('allCompRaodong.pkl','rb')
allCompany=pickle.load(f)

def getHuankuanProb(obj,yinghuan,qixian):
    tot = max(obj.x) - min(obj.x)
    t = 0
    for i in obj.y:
        if i > yinghuan:
            t += 1
    t=t/30 # 以月为单位
    tot=tot/30 # 同上
    ret=t/tot # 期限为一年能还上的概率
    ret*=12/qixian # 按期限给予反向折扣
    return ret*(1-obj.misDingDan+0.1)

def getChengjiao(pingji,lilv):
    if pingji==1: # 越小越好
        return 1-liushi.Af(lilv)
    if pingji==2:
        return 1-liushi.Bf(lilv)
    if pingji==3:
        return 1-liushi.Cf(lilv)
    else:
        return 0

def caluOne(lilv,edu,qixian,obj):
    lilv/=100

    yinghuan=edu*(1+lilv)
    huankuanProb=getChengjiao(obj.pingji,lilv)
    chengjiaoProb=getHuankuanProb(obj,yinghuan,qixian)
    return (yinghuan*huankuanProb*chengjiaoProb*qixian/12)-edu

result='企业代号,预期收益,贷款额度,利率,期限\n'

for name, comp in allCompany.items():
    if comp.pingji==4:
        result+=comp.code+',0,0,0,0\n'
    else:
        def fun(lilv, edu, qixian):
            return caluOne(lilv, edu, qixian, comp)

        rf_bo = bayes_opt.BayesianOptimization(  # 对每个公司优化
            fun,
            {
                'lilv': (4, 15),
                'edu': (100000, 1000000),
                'qixian': (1, 12)
            }
        )
        rf_bo.maximize()
        val = rf_bo.max
        result += comp.code + ',' + str(val['target']) + ',' + str(val['params']['edu']) + ',' + str(
            val['params']['lilv']) + ',' + str(val['params']['qixian']) + '\n'

print(result)